package link.chengguo.orangemall.delivery.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import link.chengguo.orangemall.delivery.DeliveryConnectUtils;
import link.chengguo.orangemall.delivery.entity.*;
import link.chengguo.orangemall.delivery.service.IDeliveryService;
import link.chengguo.orangemall.enums.OrderStatus;
import link.chengguo.orangemall.enums.ShippingStatus;
import link.chengguo.orangemall.oms.entity.OmsOrder;
import link.chengguo.orangemall.oms.entity.OmsOrderItem;
import link.chengguo.orangemall.oms.mapper.OmsOrderMapper;
import link.chengguo.orangemall.service.oms.IOmsOrderItemService;
import link.chengguo.orangemall.service.oms.IOmsOrderService;
import link.chengguo.orangemall.shms.entity.ShmsShopInfo;
import link.chengguo.orangemall.service.shms.IShmsShopInfoService;
import link.chengguo.orangemall.util.DateUtils;
import link.chengguo.orangemall.utils.CommonResult;
import link.chengguo.orangemall.utils.ValidatorUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author yzb
 * @since 2020-03-11
 */
@Service
public class DeliveryServiceImpl extends ServiceImpl<OmsOrderMapper, OmsOrder> implements IDeliveryService {

    @Resource
    private IShmsShopInfoService shopInfoService;
    @Resource
    private IOmsOrderItemService orderItemService;
    @Resource
    private IOmsOrderService orderService;

    @Override
    public boolean addOrder(OmsOrder order) {
        DOrder deliveryOrder=new DOrder();
        //商家信息
        ShmsShopInfo shopInfo=shopInfoService.getById(order.getShopId());
        if (shopInfo==null){
            throw new RuntimeException("订单店铺信息异常");
        }
        if (ValidatorUtils.isEmpty(shopInfo.getToken())){
            throw new RuntimeException("店铺："+shopInfo.getName()+" 未配置配送系统Token");
        }
        //顾客信息
        deliveryOrder.setCustomer_address(order.getReceiverDetailAddress());
        deliveryOrder.setCustomer_name(order.getReceiverName());
        deliveryOrder.setCustomer_phone(order.getReceiverPhone());
        deliveryOrder.setCustomer_lat(order.getReceiverLng());
        deliveryOrder.setCustomer_lng(order.getReceiverLng());
        //订单信息
        deliveryOrder.setThird_order_id(order.getOrderSn());
        deliveryOrder.setThird_serial_number("1");//订单日序号
        deliveryOrder.setExpected_time(order.getExpectTime());
        deliveryOrder.setDelivery_fee(order.getFreightAmount());
        deliveryOrder.setOrder_amount(order.getTotalAmount());
        deliveryOrder.setOrder_actual_amount(order.getPayAmount());
        deliveryOrder.setPick_payable_cost(new BigDecimal(0));
        deliveryOrder.setFinish_receivable_cost(new BigDecimal(0));
        deliveryOrder.setPayment_time(DateUtils.format(order.getPaymentTime()));
        deliveryOrder.setShop_take_time(DateUtils.format(order.getTakeTime()));
        //商品信息
        List<OmsOrderItem> list=orderItemService.getGoodsListByOrderSn(order.getOrderSn());
        List<DGoodsDetail> goodsDetails=new ArrayList<>();
        DGoodsDetail goodsDetail;
        int number=0;
        for (OmsOrderItem item:list){
            goodsDetail=new DGoodsDetail();
            goodsDetail.setGoods_count(item.getProductQuantity());
            goodsDetail.setGoodsAttr(item.getProductAttr());
            goodsDetail.setGoodsBarcode(item.getProductSkuCode());
            goodsDetail.setGoodsImage(item.getProductPic());
            goodsDetail.setGoodsName(item.getProductName());
            goodsDetail.setGoodsPrice(item.getProductPrice());
            goodsDetails.add(goodsDetail);
            number+=item.getProductQuantity();
        }
        deliveryOrder.setGoods_count(number);
        deliveryOrder.setGoods_detail(goodsDetails);
        //提交订单
        CommonResult result= DeliveryConnectUtils.addOrder(shopInfo.getToken(),deliveryOrder);
        System.out.println(result.toString());
        return result.getCode()==CommonResult.SUCCESS;
    }

    @Override
    public boolean cancelOrder(Long orderId, int reasonId, String reson) {
        OmsOrder omsOrder=orderService.getById(orderId);
        //商家信息
        ShmsShopInfo shopInfo=shopInfoService.getById(omsOrder.getShopId());
        if (shopInfo==null){
            throw new RuntimeException("订单店铺信息异常");
        }
        if (ValidatorUtils.isEmpty(shopInfo.getToken())){
            throw new RuntimeException("店铺："+shopInfo.getName()+" 未配置配送系统Token");
        }
        CancelReason cancelReason=new CancelReason();
        cancelReason.setCancel_reason_id(reasonId);
        cancelReason.setCancel_reson(reson);
        cancelReason.setThrid_order_id(omsOrder.getOrderSn());
        CommonResult result= DeliveryConnectUtils.cancelOrder(shopInfo.getToken(),cancelReason);
        return result.getCode()==CommonResult.SUCCESS;
    }

    @Override
    public DOrderStatus getOrderStatus(Long orderId) {
        OmsOrder omsOrder=orderService.getById(orderId);
        //商家信息
        ShmsShopInfo shopInfo=shopInfoService.getById(omsOrder.getShopId());
        if (shopInfo==null){
            throw new RuntimeException("订单店铺信息异常");
        }
        if (ValidatorUtils.isEmpty(shopInfo.getToken())){
            throw new RuntimeException("店铺："+shopInfo.getName()+" 未配置配送系统Token");
        }
        CommonResult result= DeliveryConnectUtils.queryOrderStatus(shopInfo.getToken(),omsOrder.getOrderSn());
        if (result.getCode()==CommonResult.SUCCESS){
            DOrderStatus dOrderStatus= (DOrderStatus) JSON.parse((String) result.getData());
            return dOrderStatus;
        }
        return null;
    }

    @Override
    public DOrderStatus getRiderLocation(Long orderId) {
        OmsOrder omsOrder=orderService.getById(orderId);
        //商家信息
        ShmsShopInfo shopInfo=shopInfoService.getById(omsOrder.getShopId());
        if (shopInfo==null){
            throw new RuntimeException("订单店铺信息异常");
        }
        if (ValidatorUtils.isEmpty(shopInfo.getToken())){
            throw new RuntimeException("店铺："+shopInfo.getName()+" 未配置配送系统Token");
        }
        CommonResult result= DeliveryConnectUtils.queryRiderLocation(shopInfo.getToken(),omsOrder.getOrderSn());
        if (result.getCode()==CommonResult.SUCCESS){
            DOrderStatus dOrderStatus= (DOrderStatus) JSON.parse((String) result.getData());
            return dOrderStatus;
        }
        return null;
    }

    @Override
    public boolean evaluateRider(Long orderId, DRiderEvaluate riderEvaluate) {
        OmsOrder omsOrder=orderService.getById(orderId);
        //商家信息
        ShmsShopInfo shopInfo=shopInfoService.getById(omsOrder.getShopId());
        if (shopInfo==null){
            throw new RuntimeException("订单店铺信息异常");
        }
        if (ValidatorUtils.isEmpty(shopInfo.getToken())){
            throw new RuntimeException("店铺："+shopInfo.getName()+" 未配置配送系统Token");
        }
        riderEvaluate.setThrid_order_id(omsOrder.getOrderSn());
        CommonResult result= DeliveryConnectUtils.riderEvaluate(shopInfo.getToken(),riderEvaluate);
        return result.getCode()==CommonResult.SUCCESS;
    }

    /**
     * 接收回调后更新订单状态
     * @param orderStatus
     * @return
     */
    @Transactional
    @Override
    public boolean updateOrderStatus(DOrderStatus orderStatus, ShmsShopInfo shopInfo) {
        //查询匹配的订单
        OmsOrder order= orderService.getOne(new QueryWrapper<OmsOrder>().eq("order_sn",orderStatus.getThird_order_id()));
        if (!order.getShopId().equals(shopInfo.getId())){
            throw new RuntimeException("订单与店铺不匹配");
        }
        order.setShippingStatus(orderStatus.getStatus());
        if (orderStatus.getStatus()>= ShippingStatus.WaitPickUp.getValue() && order.getStatus()<=ShippingStatus.Finished.getValue()){//抢单成功
            //接单到完成需要提交骑手信息
            if (orderStatus.getRider_id()!=null){
                order.setRiderId(Long.parseLong(orderStatus.getRider_id()));
            }
            order.setRiderName(orderStatus.getRider_name());
            order.setRiderPhone(orderStatus.getRider_phone());
        }else if(orderStatus.getStatus()==ShippingStatus.Canceled.getValue()){
            order.setCancelReasonId(Integer.parseInt(orderStatus.getCancel_reason_id()));
            order.setCancelReason(orderStatus.getCancel_reason());
        }
        if (orderStatus.getStatus()==ShippingStatus.Finished.getValue()){
            //配送完成。更新主状态
            order.setStatus(OrderStatus.Finished.getValue());
        }
        return orderService.updateById(order);
    }
}
